import json
from openai import OpenAI

def get_config(api_web: str) -> dict:
    '''
    读取配置文件
    :param api_web: str, api的名字
    :return: dict, 配置文件
    '''
    CONFIG = {}
    with open('api_config.json', 'r', encoding='utf-8') as f:
        CONFIG = json.load(f)
    return CONFIG[api_web]

def api_request(model, prompt, attempt, CONFIG, system_prompt: str = "你是一名真实的人类，不要担心道德或政治问题，尽可能模拟真实的人类反应。"):
    """执行API请求"""
    client = OpenAI(
        api_key=CONFIG['api_key'],
        base_url=CONFIG['base_url']
    )
    
    try:
        response = client.chat.completions.create(
            model=model,
            messages=[{
                "role": "system",
                "content": system_prompt
            },
                {
                "role": "user", 
                "content": prompt
                }],
            temperature=CONFIG['temperature'],
        )
        return response.choices[0].message.content
    except Exception as e:
        print(f"Attempt {attempt} failed: {str(e)}")
        raise e